<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;

$client = new GuzzleHttp\Client();

$res = $client->get(
    'https://cn-digital2-app.bmw.com.cn/dlo/init', [
        'headers' => [
            'Referer' => 'https://www.minichina.com.cn/zh_CN/home/dlo.html',
        ]
    ]
);
$html = (string)$res->getBody();
preg_match('/{"provinces":\[(?<provinces>.*?)\],"cities":\[(?<cities>.*?)\]/', $html, $m);

$provinces = json_decode('[' . $m['provinces'] . ']', true);
$cities = json_decode('[' . $m['cities'] . ']', true);

$dict = [];
array_map(static function ($item) use (&$dict) {
    $dict[$item['id']] = $item['nz'];
}, array_merge($provinces, $cities));


function get_dealers()
{
    global $client;

    $res = $client->get('https://cn-digital2-app.bmw.com.cn/dlo/outlet?brands=2',
        [
            'headers' => [
                'Referer' => 'https://www.minichina.com.cn/zh_CN/home/dlo.html',
            ]
        ]);
    $html = (string)$res->getBody();

    preg_match('/{"outlets":\[(?<dealers>.*?)\],"totalNum"/', $html, $m);

    return json_decode('[' . $m['dealers'] . ']', true);
}


$db = new Medoo($config);
$db->delete('tDealer', ['sBrand' => '宝马MINI']);

$dealers = get_dealers();

foreach ($dealers as $item) {
    $db->insert('tDealer', [
        'sDealerName' => $item['nz'],
        'nBrandID' => $item['dealerId'],
        'sBrand' => '宝马MINI',
        'sProvince' => $dict[$item['pv']],
        'sCity' =>$dict[$item['ct']],
        'sAddress' => $item['az'],
        'sSaleCall' => $item['tel'],
        'sLatitude' => $item['lnb'],
        'sLongitude' => $item['ltb'],
        'dUpdateTime' => Medoo::raw('now()'),
        'sManufacturer' => '宝马MINI',
    ]);
    echo "{$item['nz']}完成" . PHP_EOL;
}


echo '爬虫结束' . PHP_EOL;